package de.tum.in.eist.im.client;

import java.util.Date;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.event.dom.client.ClickHandler;

import de.tum.in.eist.im.client.domain.Message;
import de.tum.in.eist.im.shared.FieldVerifier;


public class ChatBar {
	private ChatServiceAsync chatService;
	private final EIST_IM client;
	//TextArea + SendButton
	final HorizontalPanel chatBar = new HorizontalPanel();
	final TextArea newMessageArea = new TextArea();
	final Button sendButton = new Button("SEND");
	/**
	 * creates ChatBar and adds the Handlers.
	 * @param chatS
	 * @param c
	 */
	public ChatBar(ChatServiceAsync chatS, EIST_IM c){
		sendButton.addStyleName("sendButton");
		chatBar.add(newMessageArea);
		newMessageArea.setStyleName("chatTableTextArea");
		chatBar.add(sendButton);
		chatService = chatS;
		client = c;
		newMessageArea.addKeyPressHandler(new KeyPressHandler(){
			@Override
			public void onKeyPress(KeyPressEvent event) {
				if(!event.isAnyModifierKeyDown()) {
					if(event.getCharCode() == KeyCodes.KEY_ENTER)
						sendMessage();
				}
			}
		});
		sendButton.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				sendMessage();
				
			}
		});
	}
	/**
	 * send the message from the TextArea.
	 */
	private void sendMessage() {
		String text = newMessageArea.getText();
		text.trim();
		if(FieldVerifier.isValid(text)){
		final Message message = new Message( new Date().getTime() , text , client.getUser()); 
		AsyncCallback<Void> callback = new AsyncCallback<Void>(){

			@Override
			public void onFailure(Throwable caught) {
				client.setErrorLabelText("Failed to send Message");
				
			}

			@Override
			public void onSuccess(Void result) {
				newMessageArea.setText("");
			}
		};
		chatService.sendMessage(message, callback);
		}
	}
	public HorizontalPanel getHPanel(){
		return chatBar;
	}
}
